package com.sun.mvc.converter;

import java.io.File;
import java.util.UUID;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class UploadFileConverter implements Converter<MultipartFile, String> {

	@Override
	public String convert(MultipartFile file) {
		try {
			if (file != null) {
				// 1.获取文件后缀
				String extName = StringUtils.getFilenameExtension(file.getOriginalFilename());
				// 2.找到新文件存储路径
				String uploadDir = "C:/upload/";
				// 3.生成新文件名为随机数。
				String id = UUID.randomUUID().toString();
				File realFile = new File(uploadDir, id + extName);
				// 4.转存file文件到存储目录
				// FileUtils.copyFile(file, realFile);
				file.transferTo(realFile);
				System.out.println(file.getContentType() + "--" + file.getName() + "--" + file.getOriginalFilename() + "--" + file.getSize() + "--");
				return id;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
